package com.frxuexi.apps

import android.os.Environment
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.BaseApp
import com.frxuexi.lib_base.BaseTitle
import com.frxuexi.lib_base.HttpType
import com.frxuexi.lib_base.UiState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

@Composable
fun AppsPage(navHostController: NavHostController,vm:AppsViewModel= hiltViewModel()) {
    var list = remember {
        SnapshotStateList<AppsData>()
    }
    var isShowProgress by remember {
        mutableStateOf(false)
    }

    /**
     * 安装
     */
    var launch by remember {
        mutableStateOf(false)
    }

    var cur_process by remember {
        mutableStateOf(0f)
    }
    val scope = rememberCoroutineScope()
    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        if(it.type==HttpType.DOWNLOAD){
                            isShowProgress=false
                            ToastUtils.showLong("下载成功")
                            navHostController.popBackStack()
                        }else {
                            Log.i("===", it.data.toString())
                            list.addAll(it.data as Collection<AppsData>)
                        }
                    }
                    is UiState.onError->{
                        Log.i("===",it.msg)
                    }

                    else -> {}
                }
            }
        }
        vm.sendIntent(AppsIntent.getApps(mapOf("userId" to 1,"page" to 1)))
    })


    Box(contentAlignment = Alignment.Center) {
        Column(Modifier.padding(10.dp)) {
            BaseTitle(title = "在线应用", navHostController = navHostController)
            list.forEach {
                Text(text = it.title)
                LazyVerticalGrid(columns = GridCells.Fixed(3),content = {
                    items(it.appsList){
                        AppsItem(entity = it,vm, myClick = {
                            isShowProgress=true
                        },longClick={
                            Log.i("===","长按")
                            launch=true
                            scope.launch {
                                for (i in 1..100){
                                    cur_process=i.toFloat()/100
                                    delay(50)
                                }
                                launch=false
                                ToastUtils.showLong("安装完成")
                            }
                        })
                    }
                })
            }
        }

        if(isShowProgress){
            CircularProgressIndicator()
        }
        if(launch){
            LinearProgressIndicator(progress = cur_process,
                Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 40.dp))
        }
    }



}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun AppsItem(entity: AppsEntity,vm: AppsViewModel,myClick: () -> Unit,longClick:() -> Unit){
    var isShow by remember {
        mutableStateOf(false)
    }
    val file = BaseApp.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
    Column (horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.combinedClickable(
        onClick={isShow=true},
        onLongClick = {
            Log.i("===","长按了")
            longClick()
        })){
        AsyncImage(model = entity.appIcon, contentDescription = "", modifier = Modifier.size(40.dp))
        Text(text = entity.appName)
    }

    if(isShow){
        AlertDialog(onDismissRequest = { isShow=false}, confirmButton = { TextButton(onClick = {
            vm.sendIntent(AppsIntent.downloadApk(entity.apkUrl, File(file,entity.appName+".apk")))
            isShow=false
            myClick()
        }) {
            Text(text = "确认")
        } },dismissButton={
            TextButton(onClick = {
                isShow=false
            }) {
                Text(text = "取消")
            }
        }, title = { Text(text = "下载提醒")},
            text = { Text(text = "是否要下载${entity.appName}吗？")})
    }
}